package com.zryc.shop.ums.service.impl;

import com.zryc.shop.ums.entity.Role;
import com.zryc.shop.ums.mapper.ResourceMapper;
import com.zryc.shop.ums.mapper.RoleMapper;
import com.zryc.shop.ums.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 后台用户角色表 服务实现类
 * </p>
 *
 * @author LiYe
 * @since 2023-02-02
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Override
    @Transactional //让当前方法内的所有操作同属于一个事务（要么都做，要么都不做）
    public Boolean allocMenu(Long roleId, String menuIds) {
        baseMapper.deleteRoleMenuRelation(roleId);//1.先删除已有的（角色-菜单）关联关系
        if (StringUtils.isEmpty(menuIds))
            return true;
        //2.重新分配（角色-菜单）关联关系
        for (String menuId:menuIds.split(",")) {
            baseMapper.insertRoleMenuRelation(roleId, Long.valueOf(menuId));
        }
        return true;
    }
    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    @Transactional
    public Boolean allocResource(Long roleId, String resourceIds) {
        resourceMapper.deleteRoleResourceRelation(roleId);
        if (StringUtils.isEmpty(resourceIds))
            return true;
        for (String resourceId:resourceIds.split(",")) {
            resourceMapper.insertRoleResourceRelation(roleId, Long.valueOf(resourceId));
        }
        return true;
    }

    @Override
    public List<Role> getListByAdminId(Long adminId) {
        return baseMapper.selectListByAdminId(adminId);
    }

    @Override
    @Transactional //让当前方法内的所有操作同属于一个事务（要么都做，要么都不做）
    public Boolean allocRole(Long adminId, String roleIds) {
        //1.先将原有的角色关系删除
        baseMapper.deleteByAdminId(adminId);
        if (StringUtils.isEmpty(roleIds)) //如果roleIds为null或空字符串，则直接返回无需进行步骤2
            return true;
        //2.再分配新角色关系
        String[] idsArray = roleIds.split(",");//1,2,3 => [1,2,3]
        for (String roleId : idsArray) {
            baseMapper.insertAdminRoleRelation(adminId, Long.valueOf(roleId));
        }
        return true;
    }

}
